// @Author EthanScriptOn
// @Desc
package config_source_loader

import (
	"errors"
	"gitee.com/fatzeng/srf_switch_basic_components/util"
	"gitee.com/fatzeng/srf_switch_config/config_define"
)

type CliSourceLoader struct {
	*ArgsBaseSourceLoader
}

func (c *CliSourceLoader) ShouldExecute(checkerInstance interface{}) (bool, error) {
	shouldExecute, err := c.ArgsBaseSourceLoader.ShouldExecute(checkerInstance)
	if err != nil || !shouldExecute {
		return shouldExecute, err
	}
	if !c.ctx.IsOpenCli() {
		return false, errors.New("the cli configuration parsing function is not enabled")
	}
	return true, nil
}

func (c *CliSourceLoader) Initialization() (err error) {
	keyValuePairsSlicing := GenerateSourceLoaderSlicing("=", true, 2)
	multiKeySlicing := GenerateSourceLoaderSlicing(".", true, -1)
	c.ConfigSourceLoaderSteps, err = GenerateAllowableCutFileBaseSourceLoaderSteps(c, keyValuePairsSlicing, multiKeySlicing, `(\\w+)\\[(\\d+)\\]`)
	if err != nil {
		return err
	}
	c.ArgsBaseSourceLoader, err = GenerateArgsBaseSourceLoader(c, c.GetConfigSourceType())
	if err != nil {
		return err
	}
	return c.ArgsBaseSourceLoader.Initialization()
}

func (c *CliSourceLoader) GetConfigSourceType() config_define.ConfigSourceType {
	return config_define.CLI
}

func (c *CliSourceLoader) LoadConfigSource() (interface{}, error) {
	sourceLoaderResult := new(SourceLoaderResult)
	sourceLoaderResult.SetConfigSourceType(c.GetConfigSourceType())
	envLoadData := util.CommandArgsLoad()
	loadNodes, err := c.ArgsBaseSourceLoader.LoadSourceLoaderNodes(c.ArgsBaseSourceLoader.ConvertToLine(envLoadData))
	if err != nil {
		return nil, err
	}
	if err = c.ArgsBaseSourceLoader.PerfectSourceLoaderResultWithSegmentInformation(sourceLoaderResult, loadNodes); err != nil {
		return nil, err
	}
	return sourceLoaderResult, nil
}
